package com.neu.flashmall.product.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.common.constant.ResultCodeEnum;
import com.neu.common.to.AuthorityCheckTo;
import com.neu.common.utils.Result;
import com.neu.flashmall.product.feign.MSFeignService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class AuthorityCheckInterceptor implements HandlerInterceptor {
    @Resource
    private MSFeignService authorityFeignService;

    @Resource
    private ObjectMapper objectMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())) return true;
        String url = request.getServletPath();
        String token = request.getHeader("Token");
        AuthorityCheckTo authorityCheckTo = new AuthorityCheckTo(url,token);
        Result result = authorityFeignService.authorityCheck(authorityCheckTo);
        if(result.getData().equals(true)){
            return true;
        }
        return toReturnFalse(response);
    }

    private boolean toReturnFalse(HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        Result result = Result.error().setCodeAndMessage(ResultCodeEnum.HAVE_NO_RIGHT);
        String json = objectMapper.writeValueAsString(result);
        writer.write(json);
        return false;
    }
}
